<?php
namespace app\admin\controller;

use think\Db;
use think\Request;

class System extends Common {
    private $obj;
    public function _initialize() {
        parent::_initialize();
        $this->obj = model('config');
    }

    /**
     * 系统配置
     * @return \think\response\Json|\think\response\View
     */
    public function index() {
        if (request()->isAjax()) {
            Db::startTrans();
            try {
                $request = Request::instance();
                $data = $request->param();

                foreach ($data as $k => $v) {
                    // $v = str_replace('"', '\"', trim($v));
                    $rs = model('config')->get(['name' => $k]);
                    if ($rs) {
                        model('config')->where(['name' => $k])->update(['value' => $v]);
                    } else {
                        model('config')->insert(['name' => $k,'value' => $v]);
                    }
                }
                // 提交事务
                Db::commit();
                update_config();
                return json(['code' => 200,'msg' => 'SUCCESS']);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return json(['code' => 0,'msg' => $e->getMessage()]);
            }
        } else {
            $system = config('system');
            if ($system)
                $this->assign('data', $system);

            return view();
        }
    }
}
